const userService = require('../service/user.service')
const errorTypes = require('../error/error-types')
const md5password = require("../utils/password")

// 验证用户
const verifyUser = async (ctx, next) => {
  // 1.获取用户名, 密码
  const { nickname, password } = ctx.request.body
  // 2.判断用户名, 密码不为空
  if (!nickname || !password) {
    const error = new Error(errorTypes.NICKNAME_OR_PASSWORD_IS_REQUIRED)
    return ctx.app.emit('error', error, ctx)
  }
  // 3.判断用户名不重复
  const result = await userService.getUserByNickname(nickname)
  // @ts-ignore
  if (result.length > 0) {
    const error = new Error(errorTypes.USER_ALREADY_EXISTS)
    return ctx.app.emit('error', error, ctx)
  }
  // 4.验证通过
  await next()

}

// 密码加密
const handlePassword = async (ctx, next) => {
  let { password } = ctx.request.body
  ctx.request.body.password = md5password(password)
  await next()
}

// 验证密码
const verifyPassword = async (ctx, next) => {
  const { id } = ctx.user
  const { currPassword, newPassword } = ctx.request.body
  const result = await userService.findUserByPassword(id, md5password(currPassword))
  if (!result) {
    const error = new Error(errorTypes.PASSWORD_IS_INCORRENT)
    return ctx.app.emit('error', error, ctx)
  }
  ctx.user.password = md5password(newPassword)
  await next()
}

module.exports = {
  verifyUser,
  handlePassword,
  verifyPassword
}
